<?
require_once('functions.php');

function GetOrderItems()
{
        $conn = GetConnection();
        return $conn->query('SELECT * FROM 2012WP_OrdersItems');
}
function BlankOrderItem()
{
        return array('Orders_id'=>null,'Products_id'=>null, 'ProductQuantity'=>null, 'ProductPrice'=>null, 'created_at'=>null,'updated_at'=>null,'id'=>null);
}
function GetOrderItem($id)
{
        $conn = GetConnection();
        $sql = "SELECT * FROM 2012WP_OrdersItems WHERE id=$id";
        $results = $conn->query($sql);
        //echo $sql;
        $row = $results->fetch_assoc();
        $conn->close();
        return $row;
}
function SaveOrderItem(&$row)
{
        $conn = GetConnection();
        $row2 = EscapeRow($row, $conn);
        if(empty($row['id']))
        {
                $sql =  "Insert 2012WP_OrdersItems (2012WP_Orders_id, 2012WP_Products_id, ProductQuantity, ProductPrice, created_at) "
                        .       " Values ('$row2[Orders_id]','$row2[Products_id]', '$row2[ProductQuantity]', '$row2[ProductPrice]', NOW() ) ";
        }else{
                $sql =  "UPDATE 2012WP_OrdersItems "
                        .       "Set 2012WP_Orders_id='$row2[Orders_id]', 2012WP_Products_id='$row2[Products_id]', ProductQuantity='$row2[ProductQuantity]',  ProductPrice='$row2[ProductPrice]' "
                        .       "WHERE id=$row2[id] ";
        }
        $results = $conn->query($sql);
        //echo $sql;
        $error = $conn->error;
        if(empty($row['id']) && empty($error))
        {
                $row['id'] = $conn->insert_id;
        }
        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}
function DeleteOrderItem($id)
{
        $conn = GetConnection();
        $sql =  "DELETE FROM 2012WP_OrdersItems WHERE id=$id";
        $results = $conn->query($sql);
        //echo $sql;
        $error = $conn->error;
        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}
function ValidateOrderItem($row)
{
        $errors = array();
		if(!is_numeric($row['Orders_id'])) $errors['Orders_id'] = 'Orders_id must be a number';
        if(empty($row['Orders_id'])) $errors['Orders_id'] = 'Orders_id is required';
		if(!is_numeric($row['Products_id'])) $errors['Products_id'] = 'Products_id must be a number';
        if(empty($row['Products_id'])) $errors['Products_id'] = 'Products_id is required';
		if(!is_numeric($row['ProductQuantity'])) $errors['ProductQuantity'] = 'ProductQuantity must be a number';
        if(empty($row['ProductQuantity'])) $errors['ProductQuantity'] = 'ProductQuantity is required';
		if(!is_numeric($row['ProductPrice'])) $errors['ProductPrice'] = 'ProductPrice must be a number';
        if(empty($row['ProductPrice'])) $errors['ProductPrice'] = 'ProductPrice is required';
       
        return count($errors) == 0 ? true : $errors;
}
